﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using Microsoft.Kinect;
using System.IO;
using System.Windows.Shapes;
using AlphaBeatSoundEngine;
using KinectDrawer;
using System.Windows.Media.Animation;



namespace KinectAlphaBeat
{
    /// <summary>
    /// Logique d'interaction pour MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {

        private KinectSensor sensor;
        private WriteableBitmap kinectTempBitmap;
        private List<List<System.Drawing.Point>> kinectTempPoint;
        private WriteableBitmap colorBitmap;
        private byte[] kinectTempColorPixels;
        private byte[] colorPixels;
        BitmapImage bmp;
        Image img;
        String _filePath;

        private TextBox[] tempTextBox = new TextBox[8];
        //  enum drawingState { isDrawing, insufficientPixels, notDetected };

        private delegate void TBXTextChanger(string text);
        private delegate void TBXChangeInfoState(string text);
        private delegate void TBXBorderChanger(int index);
        private delegate void TBXChangeState(DrawerRealtimeDrawingEventArgs e);

        public MainWindow()
        {
            InitializeComponent();
            tempTextBox[0] = tb_displayLetter1;
            tempTextBox[1] = tb_displayLetter2;
            tempTextBox[2] = tb_displayLetter3;
            tempTextBox[3] = tb_displayLetter4;
            tempTextBox[4] = tb_displayLetter5;
            tempTextBox[5] = tb_displayLetter6;
            tempTextBox[6] = tb_displayLetter7;
            tempTextBox[7] = tb_displayLetter8;


            bmp = new BitmapImage();
            img = new Image();


            // Allocate space to put the pixels we'll receive
            this.colorPixels = new byte[640 * 480 * 32];

            // This is the bitmap we'll display on-screen
            this.colorBitmap = new WriteableBitmap(640, 480, 96.0, 96.0, PixelFormats.Bgr32, null);

            // Set the image we display to point to the bitmap where we'll put the image data
            this.ColorImage.Source = this.colorBitmap;
        }

        private void WindowLoaded(object sender, RoutedEventArgs e)
        {

        }

        /// <summary>
        /// Execute shutdown tasks
        /// </summary>
        /// <param name="sender">object sending the event</param>
        /// <param name="e">event arguments</param>
        private void WindowClosing(object sender, System.ComponentModel.CancelEventArgs e)
        {
        }

        public void AlphaBeatChangedLetter(object sender, AlphaBeatWillPlayLetterEventArgs e)
        {
            WriteToTextBox(e.LetterIndex.ToString());
            ChangeBorderColorTextBox(e.LetterIndex);
        }

        public void ChangeBorderColorTextBox(int index)
        {
            for (int i = 0; i < tempTextBox.Length; i++)
            {

                if (tempTextBox[i].Dispatcher.CheckAccess())
                {
                    tempTextBox[i].BorderBrush = Brushes.Gray;

                }
                else
                {
                    tempTextBox[index].Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new TBXBorderChanger(this.ChangeBorderColorTextBox), index);
                }

            }

            if (tempTextBox[index].Dispatcher.CheckAccess())
            {
                tempTextBox[index].BorderBrush = Brushes.Red;

            }
            else
            {
                tempTextBox[index].Dispatcher.Invoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                new TBXBorderChanger(this.ChangeBorderColorTextBox), index);
            }
        }

        private void WriteToTextBox(string text)
        {
          /*  if (this.tb_displayIndex.Dispatcher.CheckAccess())
            {
                this.tb_displayIndex.Text = text;

            }

            else
            {
                this.tb_displayIndex.Dispatcher.Invoke(
                System.Windows.Threading.DispatcherPriority.Normal,
                new TBXTextChanger(this.WriteToTextBox), text);
            }*/
        }


        public void DrawerSentNewRealtimePicture(object sender, DrawerRealtimeDrawingEventArgs e)
        {
            BitmapSource source = e.CameraAndDrawingColorBitmap;
            int stride = source.PixelWidth * (source.Format.BitsPerPixel / 8);
            source.CopyPixels(colorPixels, stride, 0);
            this.colorBitmap.WritePixels(
                        new Int32Rect(0, 0, this.colorBitmap.PixelWidth, this.colorBitmap.PixelHeight),
                        colorPixels,
                        this.colorBitmap.PixelWidth * sizeof(int),
                        0);

            DisplayStateDetection(e);
        }


        //public void DisplayFrame
        /*    public void DrawerSentNewRealtimePicture(object sender, DrawerRealtimeDrawingEventArgs e)
            {
                BitmapSource source = e.CameraColorBitmap;
                int stride = source.PixelWidth * (source.Format.BitsPerPixel / 8);
                source.CopyPixels(colorPixels, stride, 0);
                this.colorBitmap.WritePixels(
                            new Int32Rect(0, 0, this.colorBitmap.PixelWidth, this.colorBitmap.PixelHeight),
                            colorPixels,
                            this.colorBitmap.PixelWidth * sizeof(int),
                            0);
            }*/




        public void DisplayWord(string word)
        {
            //toto

            Char[] tempWord = word.ToCharArray();

            if (tempWord.Length > 8)
                return;

            //  tb_test.Text = tempWord.Length.ToString();
            int i;
            for (i = 0; i < tempWord.Length; i++)
            {
                tempTextBox[i].Text = tempWord[i].ToString();

            }

            for (; i < 8; i++)
            {
                tempTextBox[i].Text = String.Empty;
            }

        }


        private void DisplayStateDetection(DrawerRealtimeDrawingEventArgs e)
        {

            if (e.UserIsCurrentlyDrawing.Equals(DrawingState.UserIsDrawing))
            {
                if (this.CercleRouge.Dispatcher.CheckAccess() && this.CercleVert.Dispatcher.CheckAccess())
                {
                    CercleVert.Visibility = System.Windows.Visibility.Visible;
                    CercleRouge.Visibility = System.Windows.Visibility.Collapsed;
                    MoveTo(CercleVert, Convert.ToDouble(e.CurrentDetectionPoint.X), Convert.ToDouble(e.CurrentDetectionPoint.Y));
                }
                else
                {
                    this.CercleRouge.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new TBXChangeState(this.DisplayStateDetection), e);

                    this.CercleVert.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new TBXChangeState(this.DisplayStateDetection), e);
                }
            }
            else if (e.UserIsCurrentlyDrawing.Equals(DrawingState.UnsufficentDetection))
            {

                if (this.CercleRouge.Dispatcher.CheckAccess() && this.CercleVert.Dispatcher.CheckAccess())
                {
                    CercleVert.Visibility = System.Windows.Visibility.Collapsed;
                    CercleRouge.Visibility = System.Windows.Visibility.Visible;
                    MoveTo(CercleRouge, Convert.ToDouble(e.CurrentDetectionPoint.X), Convert.ToDouble(e.CurrentDetectionPoint.Y));
                }
                else
                {
                    this.CercleRouge.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new TBXChangeState(this.DisplayStateDetection), e);

                    this.CercleVert.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new TBXChangeState(this.DisplayStateDetection), e);
                }

            }

            else if (e.UserIsCurrentlyDrawing.Equals(DrawingState.NoDetection))
            {
                if (this.CercleRouge.Dispatcher.CheckAccess() && this.CercleVert.Dispatcher.CheckAccess())
                {
                    CercleVert.Visibility = System.Windows.Visibility.Collapsed;
                    CercleRouge.Visibility = System.Windows.Visibility.Collapsed;
                   
                }
                else
                {
                    this.CercleRouge.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new TBXChangeState(this.DisplayStateDetection), e);

                    this.CercleVert.Dispatcher.Invoke(
                    System.Windows.Threading.DispatcherPriority.Normal,
                    new TBXChangeState(this.DisplayStateDetection), e);
                }
            }

        }

       
        

        public void MoveTo(Image target, double newX, double newY)
        {

           // GeneralTransform transform = myCanv.TransformToAncestor(this);
           // Point offset = transform.Transform(new Point(newX, newY));
            Double posX = newX * 640;
            Double posY = newY * 480;

            posX -= 25D;
            posY -= 25D;

             Canvas.SetTop(target,posY);
             Canvas.SetLeft(target,posX);
            

            
            //target.SetValue(Canvas.LeftProperty, newX);
           // target.SetValue(Canvas.TopProperty, newY);
             
            Console.WriteLine("New coos : {0};{1}", newX, newY);

        }
        /*
                   public void DisplayStateUserInformation(object sender, DrawerRealtimeDrawingEventArgs e)
                   {


                       if (e.UserIsCurrentlyDrawing.Equals(DrawingState.UserIsDrawing))
                       {


                           if (this.label_info.Dispatcher.CheckAccess())
                           {


                           }

                           else
                           {
                               this.tb_displayIndex.Dispatcher.Invoke(
                               System.Windows.Threading.DispatcherPriority.Normal,
                               new TBXChangeState(this.DrawStateDetection), bmp);
                           }
                       }
                       else if (e.UserIsCurrentlyDrawing.Equals(DrawingState.UnsufficentDetection))
                       {
                           //bmp = ImageFromRelativePath(@"\Images\CercleRouge.png");
                           bmp.UriSource = new Uri("CercleRouge.png", UriKind.Relative);
                           if (this.ColorImage2.Dispatcher.CheckAccess())
                           {
                               Console.WriteLine("pas assez bien détecté");
                               ColorImage2.Source = bmp;

                           }

                           else
                           {
                               this.tb_displayIndex.Dispatcher.Invoke(
                               System.Windows.Threading.DispatcherPriority.Normal,
                               new TBXChangeState(this.DrawStateDetection), bmp);
                           }
                       }
                       else if (e.UserIsCurrentlyDrawing.Equals(DrawingState.NoDetection))
                       {
                           // bmp = ImageFromRelativePath(@"\Images\CercleRouge.png");
                           bmp.UriSource = new Uri("CercleRouge.png", UriKind.Relative);
                           if (this.ColorImage2.Dispatcher.CheckAccess())
                           {
                               Console.WriteLine("pas détecté");
                               ColorImage2.Source = bmp;
                               //mettre dans le label un message

                           }

                           else
                           {
                               this.tb_displayIndex.Dispatcher.Invoke(
                               System.Windows.Threading.DispatcherPriority.Normal,
                               new TBXChangeState(this.DrawStateDetection), bmp);
                           }
                       }


                   }

       */

    }
}